<script setup>
import { ref, computed, watch, provide, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useVisroleStore } from '@/stores/visrole.js'
import { useAuthStore } from '@/stores/auth.js'
import chatApi from '@/apis/chat.js'

import Drawer from '@/components/common/Drawer.vue'
import RoleCollapse from '@/components/visrole/RoleCollapse.vue'

const route = useRoute()
const router = useRouter()

const visroleStore = useVisroleStore()
const authStore = useAuthStore()

const drawerRef = ref(null)

const collapseRoles = computed(() => {
  const list = [...visroleStore.categories]
  return list.map((category) => {
    return {
      id: category.id,
      name: category.name,
      show: category?.show ?? true,
      roles: roles.value.filter((role) => {
        return category.id === -1 ? role.favorite : role.category_id === category.id
      }),
    }
  })
})

const categories = computed(() => {
  return [
    { id: 0, name: '全部分类' },
    { id: -1, name: '我的收藏', show: authStore.isAuthenticated },
    ...visroleStore.categories,
  ]
})
const roles = ref([]) //所有角色

const roleId = computed(() => {
  return parseInt(route.params.id || 0)
})

const getData = async () => {
  const { data: pagination } = await chatApi.role.list('visrole', {
    pageSize: 100,
  })
  roles.value = pagination.data.map((item) => {
    return {
      ...item,
      show: true,
    }
  })
}

const selectRole = (role) => {
  router.push({ name: 'visroleChat', params: { id: role.id } })
}

const navigateToList = (name) => {
  if (name === 'visrole' || name === '') {
    if (authStore.isAuthenticated && visroleStore.active?.id > 0) {
      router.replace({
        name: 'visroleChat',
        params: { id: visroleStore.active.id },
      })
    } else {
      router.replace({ name: 'visroleIndex' })
    }
  }
}

onMounted(async () => {
  if (!visroleStore.categories.length) {
    await visroleStore.getCategories()
  }
  await getData()
  //加载全部角色
  navigateToList(route.name)
})

watch(
  () => route.name,
  (name) => {
    navigateToList(name)
  }
)

navigateToList(route.name)

provide('categories', categories) //注入
provide('roles', roles)
provide('drawerRef', drawerRef)
</script>

<template>
  <div class="flex h-full bg-[--el-fill-color-lighter] text-[--el-text-color-primary]">
    <Drawer ref="drawerRef" width="w-60">
      <RoleCollapse
        :data="collapseRoles"
        @select="selectRole"
        :select-role-id="roleId"
        v-if="roles.length"
      />
    </Drawer>
    <div class="w-full">
      <RouterView />
    </div>
  </div>
</template>
